package com.liqi.web.controller.step;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.github.pagehelper.PageHelper;
import com.liqi.common.core.controller.BaseController;
import com.liqi.common.core.domain.R;
import com.liqi.common.core.page.TableDataInfo;
import com.liqi.common.utils.poi.ExcelUtil;
import com.liqi.statistics.domain.DvServiceStatistics;
import com.liqi.step.domain.TCfgBaseStep;
import com.liqi.step.domain.TRelServiceStep;
import com.liqi.step.domain.dto.BaseStepDto;
import com.liqi.step.domain.dto.StepBindServiceDto;
import com.liqi.step.service.TCfgBaseStepService;
import com.liqi.step.service.TRelServiceStepService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: lgh
 * @Date: 2022-12-15
 * @Description: 基本步骤表
 */
@RestController
@RequestMapping("/baseStep")
@Api(tags = "基础步骤表与事项关联步骤表")
public class BaseStepController extends BaseController {
    @Autowired
    private TRelServiceStepService serviceStepService;

    @Autowired
    private TCfgBaseStepService tCfgBaseStepService;

    @PostMapping("/getBaseStepList")
    @ApiOperation("获取基础步骤表列表")
    @ApiResponses({@ApiResponse(code = 200, message = "成功", response = TCfgBaseStep.class)})
    public TableDataInfo getBaseStepList(@Validated @RequestBody BaseStepDto baseStep) {
        PageHelper.startPage(baseStep.getPageNum(), baseStep.getPageSize());
        List<TCfgBaseStep> list = tCfgBaseStepService.getBaseStepList(baseStep);
        return getDataTable(list);
    }

    @PostMapping("/addStep")
    @ApiOperation("新增基本步骤")
    public R addStep(@Validated @RequestBody TCfgBaseStep baseStep) {
        int count = tCfgBaseStepService.count(new QueryWrapper<TCfgBaseStep>()
                .eq("component_name", baseStep.getComponentName()).eq("status", 0));
        if (count > 0) {
            return R.fail("步骤组件名称已经存在、不能重复添加");
        }
        String username = getUsername();
        baseStep.setStatus(0);
        baseStep.setCreateBy(username);
        baseStep.setCreateTime(new Date());
        tCfgBaseStepService.save(baseStep);
        return R.ok();
    }

    @PostMapping("/delStep")
    @ApiOperation("步骤删除")
    @Transactional
    public R delStep(@RequestBody List<Integer> ids) {
        LambdaUpdateWrapper<TCfgBaseStep> up = new LambdaUpdateWrapper<>();
        up.set(TCfgBaseStep::getStatus, 1).in(TCfgBaseStep::getId, ids);
        tCfgBaseStepService.update(up);
        return R.ok();
    }

    @PostMapping("/upStep")
    @ApiOperation("修改步骤")
    public R upStep(@Validated @RequestBody TCfgBaseStep baseStep) {
        int count = tCfgBaseStepService.count(new QueryWrapper<TCfgBaseStep>()
                .eq("component_name", baseStep.getComponentName()).eq("status", 0).ne("id",baseStep.getId()));
        if (count > 0) {
            return R.fail("步骤组件名称已经存在、不能修改");
        }
        tCfgBaseStepService.updateById(baseStep);
        return R.ok();
    }

    @ApiOperation("步骤导出")
    @PostMapping("/exportStep")
    public void exportStep(HttpServletResponse response, @Validated @RequestBody BaseStepDto baseStep) {
        List<TCfgBaseStep> list = tCfgBaseStepService.getBaseStepList(baseStep);
        ExcelUtil<TCfgBaseStep> util = new ExcelUtil<TCfgBaseStep>(TCfgBaseStep.class);
        util.exportExcel(response, list, "步骤表导出");
    }

    @ApiOperation("步骤与事项关联")
    @PostMapping("/stepBindService")
    @Transactional
    public R stepBindService(@Validated @RequestBody StepBindServiceDto dto){
        // 转为实体对象存储
        String username = getUsername();
//        String username = "lgh";
        String serviceCode = dto.getServiceCode();
        String remark = dto.getRemark();
        QueryWrapper<TRelServiceStep> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<TRelServiceStep> lambda = queryWrapper.lambda();
        lambda.eq(TRelServiceStep::getServiceCode, serviceCode).eq(TRelServiceStep::getStatus,0);
        long count = serviceStepService.list(lambda).stream().count();
        if (count > 0) {
            UpdateWrapper<TRelServiceStep> updateWrapper = new UpdateWrapper<>();
            LambdaUpdateWrapper<TRelServiceStep> lambda1 = updateWrapper.lambda();
            lambda1.set(TRelServiceStep::getStatus, 1).eq(TRelServiceStep::getServiceCode,serviceCode);
            serviceStepService.update(lambda1);
            List<TRelServiceStep> collect = dto.getStepSort().stream().map(m -> {
                TRelServiceStep tRelServiceStep = new TRelServiceStep();
                tRelServiceStep.setServiceCode(serviceCode);
                tRelServiceStep.setStepId(m.getStepId());
                tRelServiceStep.setCreateBy(username);
                tRelServiceStep.setSort(m.getSort());
                tRelServiceStep.setRemark(remark);
                tRelServiceStep.setCreateTime(new Date());
                tRelServiceStep.setStatus(0);
                return tRelServiceStep;
            }).collect(Collectors.toList());
            serviceStepService.saveBatch(collect);
        }else {
            List<TRelServiceStep> collect = dto.getStepSort().stream().map(m -> {
                TRelServiceStep tRelServiceStep = new TRelServiceStep();
                tRelServiceStep.setServiceCode(serviceCode);
                tRelServiceStep.setStepId(m.getStepId());
                tRelServiceStep.setCreateBy(username);
                tRelServiceStep.setSort(m.getSort());
                tRelServiceStep.setRemark(remark);
                tRelServiceStep.setCreateTime(new Date());
                tRelServiceStep.setStatus(0);
                return tRelServiceStep;
            }).collect(Collectors.toList());
            serviceStepService.saveBatch(collect);
        }
        return R.ok();
    }

    @GetMapping("/getStepByService")
    @ApiOperation("根据事项id获取步骤")
    public R getStepByService(@ApiParam(value = "事项id",required = true)@RequestParam("serviceId")String serviceId){
        List<Map<String, Object>> mapList = serviceStepService.getStepByService(serviceId);
        return R.ok(mapList);
    }
}
